/// <reference types="chrome"/>
import React, { useEffect, useState, useRef } from 'react';
import { createRoot } from 'react-dom/client';

interface SubtitleData {
  text: string;
  timestamp: number;
  videoTime: number;
}

const formatTime = (seconds: number): string => {
  const h = Math.floor(seconds / 3600);
  const m = Math.floor((seconds % 3600) / 60);
  const s = Math.floor(seconds % 60);
  return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
};

const SubtitleItem: React.FC<{
  subtitle: SubtitleData;
  onClick: () => void;
}> = ({ subtitle, onClick }) => {
  return (
    <div
      className="p-2 hover:bg-gray-100 cursor-pointer flex items-start border-b"
      onClick={onClick}
    >
      <div className="text-sm text-gray-500 mr-2 whitespace-nowrap">
        {formatTime(subtitle.videoTime)}
      </div>
      <div className="flex-1 text-sm">{subtitle.text}</div>
    </div>
  );
};

const SidePanel: React.FC = () => {
  const [subtitles, setSubtitles] = useState<SubtitleData[]>([]);
  const listRef = useRef<HTMLDivElement>(null);

  // 加载字幕数据
  useEffect(() => {
    chrome.storage.local.get(['subtitles'], (result) => {
      setSubtitles(result.subtitles || []);
    });

    // 监听存储变化
    const handleStorageChange = (changes: { [key: string]: chrome.storage.StorageChange }) => {
      if (changes.subtitles) {
        setSubtitles(changes.subtitles.newValue || []);
      }
    };

    chrome.storage.onChanged.addListener(handleStorageChange);

    return () => {
      chrome.storage.onChanged.removeListener(handleStorageChange);
    };
  }, []);

  // 自动滚动到底部
  useEffect(() => {
    if (listRef.current) {
      listRef.current.scrollTop = listRef.current.scrollHeight;
    }
  }, [subtitles]);

  // 清空字幕
  const handleClear = () => {
    chrome.runtime.sendMessage({ type: 'CLEAR_SUBTITLES' });
  };

  // 跳转到视频时间点
  const handleSubtitleClick = (videoTime: number) => {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      const tab = tabs[0];
      if (tab.id) {
        chrome.tabs.sendMessage(tab.id, {
          type: 'SEEK_VIDEO',
          time: videoTime
        });
      }
    });
  };

  return (
    <div className="flex flex-col h-screen bg-white">
      {/* 标题栏 */}
      <div className="flex items-center justify-between p-4 border-b">
        <h1 className="text-lg font-semibold">B站字幕助手</h1>
        <button
          className="px-3 py-1 text-sm text-red-600 hover:bg-red-50 rounded"
          onClick={handleClear}
        >
          清空
        </button>
      </div>

      {/* 字幕列表 */}
      <div
        ref={listRef}
        className="flex-1 overflow-y-auto"
      >
        {subtitles.map((subtitle, index) => (
          <SubtitleItem
            key={subtitle.timestamp + index}
            subtitle={subtitle}
            onClick={() => handleSubtitleClick(subtitle.videoTime)}
          />
        ))}
      </div>

      {/* 底部状态栏 */}
      <div className="p-2 border-t text-sm text-gray-500">
        共 {subtitles.length} 条字幕
      </div>
    </div>
  );
};

// 渲染应用
const container = document.getElementById('root');
if (container) {
  const root = createRoot(container);
  root.render(
    <React.StrictMode>
      <SidePanel />
    </React.StrictMode>
  );
} 